﻿using FluentScheduler;

namespace EasyTemplate.Schedule;

public class DailyStatisticsService : ServiceBase
{
    public DailyStatisticsService()
    {
        Description = "每日数据统计服务";
    }

    /// <summary>
    /// 开始工作
    /// </summary>
    /// <param name="reason"></param>
    protected override void StartWork(string reason)
    {
        JobManager.Initialize(StartJobs());
        base.StartWork(reason);
    }

    /// <summary>
    /// 停止服务
    /// </summary>
    /// <param name="reason"></param>
    protected override void StopWork(string reason)
    {
        JobManager.Stop();
        base.StopWork(reason);
    }

    /// <summary>
    /// 一个服务启用多个任务
    /// </summary>
    /// <returns></returns>
    private Registry StartJobs()
    {
        var registry = new Registry();

        //今日统计
        registry.Schedule(Today).ToRunNow().AndEvery(3).Hours();

        //每日统计
        registry.Schedule(Daily).ToRunEvery(1).Days().At(0, 10);

        return registry;
    }

    private void Today()
    {
        Task.Run(async () =>
        {
            while (true)
            {
                try
                {
                    ServiceCore.WriteLine(this.GetType().Name, "开始统计", 1);


                    ServiceCore.WriteLine(this.GetType().Name, "结束统计", 1);
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                    ServiceCore.WriteLine(this.GetType().Name, ex.ToString(), 1);
                }

                Thread.Sleep(1000 * 60);
            }
        });
    }

    private void Daily()
    {
        Task.Run(async () =>
        {
            while (true)
            {
                try
                {
                    ServiceCore.WriteLine(this.GetType().Name, "开始统计", 1);


                    ServiceCore.WriteLine(this.GetType().Name, "结束统计", 1);
                }
                catch (Exception ex)
                {
                    Log.Error(ex.ToString());
                    ServiceCore.WriteLine(this.GetType().Name, ex.ToString(), 1);
                }

                Thread.Sleep(1000 * 60);
            }
        });
    }

}
